import request from '@/utils/request.js'
import store from '@/store/index.js'
// 请求频道
export async function channels () {
  // 用户没登录
  if (!store.state.user.token) {
    const _channels = JSON.parse(localStorage.getItem('userChannel')) || []
    if (_channels.length === 0) {
      const res = await request({ url: '/v1_0/user/channels' })
      localStorage.setItem('userChannel', JSON.stringify(res.data.channels))
      return res.data.channels
    } else {
      return _channels
    }
  } else {
    const res = await request({ url: '/v1_0/user/channels' })
    return res.data.channels
  }
}

export function articles (params) {
  return request({ url: '/v1_0/articles', params })
}
export function channelAll () {
  return request({ url: '/v1_0/channels' })
}

// 新增频道
export function userChannelsPut (channels) {
  if (store.state.user.token) {
    return request({
      url: '/v1_0/user/channels',
      method: 'put',
      data: { channels }
    })
  } else {
    localStorage.setItem('userChannel', JSON.stringify(channels))
  }
}
